<template>
  <div :class="$style.displayWrap">
    <ContentWrap :class="$style.wrap">
      <CardContainer>
        <FormContainer :column="4">
          <el-form ref="form" :model="formData" :rules="formRules" label-width="80px" :class="$style.form">
            <el-form-item prop="customerName" label="客户姓名">
              <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable @input="inputHandle" />
              <div :class="$style.vip">
                <span>{{ vip }}</span>
              </div>
            </el-form-item>
            <el-form-item prop="customerPhone" label="来电号码" :class="$style.displayDisable">
              <el-input v-model.trim="formData.customerPhone" placeholder="请输入来电号码" :disabled="callId!==''" clearable @click.native="clickCopyHandle" />
              <!-- 复制用 -->
              <input ref="copy" v-model="formData.customerPhone" style="opacity: 0;position: fixed;width:1;heigth:1;left:-100px;" type="text">
              <div :class="$style.tip">
                <span>{{ addr }}</span>
              </div>
            </el-form-item>
            <el-form-item v-if="$isShop()||$isClient()||$isCustomerCare()" prop="ivrOption" label="IVR选项">
              <el-select v-model="formData.ivrOption" disabled>
                <el-option v-for="(item,i) in ivrList" :key="i" :value="item.dictCode" :label="item.dictName" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <Button :class="$style.btnRight" type="primary" @click="confirmHandle">确认</Button>
              <!-- <Button v-if="relevance" :class="$style.btnRight" type="primary" @click="relevanceHandle">关联</Button> -->
            </el-form-item>
          </el-form>
        </FormContainer>
      </CardContainer>
      <slot></slot>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import CardContainer from '@/components/CardContainer'
import { deepCopy } from '@/utils'
import { putCreate } from '@/api/telRecord'
import { ccDict } from '@/api/dataDict'
import { member } from '@/api/member'
import { telAddr } from '@/api/telAddress'
import { mapMutations } from 'vuex'
export default {
  name: 'DisplayWrap',
  components: {
    ContentWrap,
    FormContainer,
    CardContainer
  },
  inject: ['closePage', 'checkClosePage', 'createdTelRecordHandle'],
  props: {
    callTel: {
      type: String,
      default: ''
    },
    callId: {
      type: String,
      default: ''
    },
    recordId: {
      type: String,
      default: ''
    },
    ivr: {
      type: [String, Number],
      default: ''
    },
    relevance: {
      type: [Boolean],
      default: false
    }
  },
  data() {
    return {
      ivrList: [],
      formData: {
        customerName: '', // 客户姓名
        customerPhone: '', // 来电号码
        ivrOption: '' // ivr选项
      },
      formRules: {
        customerName: [{ required: true, message: '请输入客户姓名', trigger: 'change' }], // 客户姓名
        customerPhone: [{ required: true, message: '请输入来电号码', trigger: 'change' }] // 来电号码
        // ivrOption: [{ required: true, message: '请选择ivr选项', trigger: 'change' }] // ivr选项
      },
      memberInfo: {}, // 会员信息
      entity: {}
    }
  },
  computed: {
    vip() {
      return this.memberInfo.level || '非会员'
    },
    addr() {
      if (this.entity.PROVINCE) {
        return `${this.entity.PROVINCE}·${this.entity.CITY}`
      }
      return this.entity.CITY
    }
  },
  watch: {
    callTel: {
      handler: 'telAddr',
      immediate: true
    }
  },
  created() {
    this.initFormData()
    this.getIvrList()
    this.member()
  },
  methods: {
    ...mapMutations(['SET_CALL_ADDRESS']),
    // 复制
    clickCopyHandle() {
      const copy = this.$refs.copy
      copy.select() // 选择对象
      document.execCommand('Copy')
      this.$message.success(`已复制电话号码(${this.formData.customerPhone})到剪贴板！`)
    },
    // 检查是否有通话记录
    confirmHandle() {
      return this.createdTelRecordHandle().then(() => {
        return this.saveHandle()
      })
    },
    saveHandle() {
      if (!this.recordId) {
        // this.$message.error('没有通话记录id，请刷新该标签！')
        this.$emit('createTelRecord', this.confirmHandle.bind(this)) // 创建通话记录
        return
      }
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        data.id = this.recordId
        delete data.customerPhone
        // delete data.ivrOption
        // if (!this.$isShop() || !this.$isClient()) {
        //   delete data.ivrOption
        // }
        return putCreate(data).then(res => {
          this.$message.success('通话记录保存成功！')
          this.$emit('refresh', 'save')
          // 关联姓名电话关联进工单
          this.$emit('onRelevance')
          // 关闭弹屏
          this.checkClosePage({ isSaveName: true })
        })
      })
    },
    // 姓名电话关联进工单
    relevanceHandle() {
      this.$message.success('关联成功！')
      this.$emit('onRelevance')
    },
    // 初始化formData
    initFormData() {
      this.$set(this.formData, 'customerPhone', this.callTel)
      this.$set(this.formData, 'ivrOption', this.ivr)
    },
    // 获取ivr数据字典
    getIvrList() {
      ccDict('IVR_OPTIONS').then(res => {
        this.ivrList = res.data
      })
    },
    // 向上抛出客户姓名
    inputHandle(v) {
      this.$emit('inputName', this.formData.customerName)
    },
    // 查询会员信息
    member() {
      if (!/^1\d{10}$/.test(this.callTel)) return
      member(this.callTel).then(res => {
        this.memberInfo = res.data
        if (res.data.userName) {
          this.$set(this.formData, 'customerName', res.data.userName)
          this.$emit('inputName', this.formData.customerName)
        }
      })
    },
    // 查询号码归属地
    telAddr(tel) {
      // 非手机号不查询你
      if (!/^1\d{10}/.test(tel)) {
        return
      }
      telAddr(tel).then(res => {
        this.entity = res.ENTITY
        let addr = ''
        if (this.entity.PROVINCE) {
          addr = `${this.entity.PROVINCE}·${this.entity.CITY}`
        } else {
          addr = this.entity.CITY
        }
        this.SET_CALL_ADDRESS(addr)
      }).catch(() => {
        this.$message.error('获取号码归属地失败！')
      })
    }
  }
}
</script>
<style lang='scss' module>
@import "@/styles/mixin.scss";
.displayWrap{
    margin: -20px -10px -10px;
    .displayDisable{
      [class*="is-disabled"],[class*="el-input__inner"]{
        cursor: pointer !important;
      }
    }
    .wrap{
        background:transparent;
        &>*{
            margin-bottom: 10px;
        }
      & .form{
        & [class*="el-form-item"]{
          margin-top: 5px !important;
          margin-bottom: 5px !important;
        }
      }
    }
    .vip{
        color: #FF9820;
        font-size: 12px;
        display: inline-block;
    }
    .tip{
        color: #999;
        font-size: 12px;
    }
    .btnRight{
        float: right;
        margin: 4px 0;
    }
}
</style>
